package org.blogwu.learn.multithread.chapter2.demo4;

import java.util.Date;

public class Main {

    static Object o1 = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new T2(), "t2");
        Thread t2 = new Thread(new T1(), "t2");
        t1.start();
        //Thread.sleep(100);
//        t2.start();

        t1.suspend();
        System.out.println("main:" + t1.getState());
        Thread.sleep(40000);
        t1.resume();
        System.out.println("Main end" + new Date());
    }
}

class T1 implements Runnable {

    @Override
    public void run() {
        long t1 = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + " start");
        synchronized (Main.o1) {
            System.out.println(Thread.currentThread().getName() + "  get sync");
            try {
                Thread.sleep(1000);
                //当执行Sleep睡眠中时被挂起....sleep中的时钟的不会暂挺,只是睡眠完成后不向下执行,必须等待resume
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long t2 = System.currentTimeMillis();
        System.out.println(Thread.currentThread().getName() + "  end: " + (t2 - t1) + "  " + new Date());
    }
}

/**
 * 当线程被中断时,在jstack中 线程状态还是现实为RUNNABLE
 * <p>
 * "t2" #11 prio=5 os_prio=31 tid=0x00007f9940804000 nid=0xa803 runnable [0x0000000000000000]
 * java.lang.Thread.State: RUNNABLE
 */
class T2 implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + " start");
        for (int i = 0; i < 9999; i++) {
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + "  end");
    }
}
